package com.sts.service.impl;

import com.sts.common.exception.BusinessException;
import com.sts.entity.Role;
import com.sts.entity.RolePermission;
import com.sts.mapper.RoleMapper;
import com.sts.mapper.RolePermissionMapper;
import com.sts.service.RoleService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Role> listAllRoles() {
        return roleMapper.selectList(null);
    }

    @Override
    @Transactional
    public void assignPerms(Long roleId, List<Long> permIds) {
        // 检查角色是否存在
        if(roleMapper.selectById(roleId) == null){
            throw new BusinessException("角色不存在");
        }

        //1.删除旧权限
        rolePermissionMapper.deleteByRoleId(roleId);

        //2.插入新权限
        if(permIds != null && !permIds.isEmpty()){
            List<RolePermission> list = permIds.stream()
                    .map(pid -> RolePermission.builder()
                            .roleId(roleId)
                            .permId(pid)
                            .build())
                    .collect(Collectors.toList());
            rolePermissionMapper.insertBatch(list);
        }
    }
}